package com.shycloud.mido.member.service.impl;

import java.util.List;
import java.util.concurrent.TimeUnit;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.shycloud.mido.common.core.constant.CommonConstants;
import com.shycloud.mido.common.core.constant.enums.LoginTypeEnum;
import com.shycloud.mido.common.core.exception.BusinessException;
import com.shycloud.mido.member.api.entity.Member;
import com.shycloud.mido.member.mapper.MemberMapper;
import com.shycloud.mido.member.service.WxMiniService;

import lombok.AllArgsConstructor;

@Service
@AllArgsConstructor
public class WxMiniServiceImpl implements WxMiniService {

	/** Redis 模块 */
	private RedisTemplate redisTemplate;
	/** 用户模块 mapper */
	private final MemberMapper memberMapper;

	/**
	 * 微信小程序绑定手机号
	 *
	 * @param phone    电话号
	 * @param code     验证码
	 * @param openId   微信的openId
	 * @param nickName 昵称
	 * @param header   头像
	 * @return java.lang.Boolean
	 * @author nianhua.jiang
	 * @date 2020/10/29 9:53
	 **/
	@Override
	public Boolean bindPhone(String phone, String code, String openId, String nickName,
			String header) {

		//设置redis锁，防止重复请求操作数据库
		Boolean registerRedis = redisTemplate.opsForValue()
				.setIfAbsent("miniBindPhone_" + phone, "1", 5, TimeUnit.SECONDS);

		if (!registerRedis) {
			throw new BusinessException("该账号已经绑定，无需重复绑定。");
		}

		//判断验证码是否过期
		Object codeObj = redisTemplate.opsForValue()
				.get(CommonConstants.DEFAULT_CODE_KEY + LoginTypeEnum.SMS.getType() + "@" + phone);

		if (codeObj == null) {
			redisTemplate.delete("miniBindPhone_" + phone);
			throw new BusinessException("手机验证码已过期");

		}
		if (!code.equals(codeObj.toString())) {
			redisTemplate.delete("miniBindPhone_" + phone);
			throw new BusinessException("验证码错误");
		}

		// 判断手机号是否已经绑定别的手机号 业务需求,必须注册过APP才能绑定小程序,否则无法绑定
		List<Member> members = memberMapper
				.selectList(new QueryWrapper<Member>().eq("username", phone));

		if (members.size() == 0) {
			redisTemplate.delete("miniBindPhone_" + phone);
			throw new BusinessException(2, "对应用户不存在，请联系后台管理员~~");
		}

		if (members.size() != 1) {
			redisTemplate.delete("miniBindPhone_" + phone);
			throw new BusinessException("用户数据存在问题，请联系后台管理员~~");
		}

		redisTemplate.delete("miniBindPhone_" + phone);

		if (members.get(0).getWxMiniOpenId() != null) {
			redisTemplate.delete("miniBindPhone_" + phone);
			throw new BusinessException("手机号已经绑定其他账号，请重新输入");
		}

		Member member = members.get(0);
		//微信小程序 openId
		member.setWxMiniOpenId(openId);
		//用户名
		member.setUsername(phone);
		//手机号
		member.setPhone(phone);
		//昵称
		member.setShowname(nickName);
		//头像
		member.setAvatar(header);
		//更新用户信息
		memberMapper.updateById(member);

		return true;
	}
}
